package com.txby.dplus.identify.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.txby.dplus.common.annomapper.MybatisBaseDaoCRUD;
import com.txby.dplus.common.utils.util.PageBean;
import com.txby.dplus.common.utils.util.PageList;
import com.txby.dplus.common.utils.util.RestClientUtil;
import com.txby.dplus.core.util.QuartzFactoryUtil;
import com.txby.dplus.identify.util.ConfigUtil;

public class UploadDataJobTask implements Job {
	private static Logger logger = LoggerFactory.getLogger(UploadDataJobTask.class);
	public static String defaultJobName = "UploadDataJobTask";
	public static String uploadUrl;
	public static ConfigUtil cu;
	public static MybatisBaseDaoCRUD mBaseDao;

	private int id = 0;

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		JobDataMap dataMap = context.getJobDetail().getJobDataMap();
		 mBaseDao = (MybatisBaseDaoCRUD) dataMap.get("mBaseDao");
		cu = (ConfigUtil) dataMap.get("cu");
		uploadUrl = cu.getUploadUrl();
		getDatas(mBaseDao);
	}

	private void getDatas(MybatisBaseDaoCRUD mBaseDao) {
		try {
			Map m = getRestData(cu.getAreaCode());
			if (m != null && m.containsKey("checkdate")) {
				String checkdate = m.get("checkdate").toString();

				logger.info(new Date()+"==开始查询数据准备上传");
				String addSql = " ,'" + cu.getAreaCode() + "'  as areaCode ";
				// 首先根据时间获取数据
				String sql = "select t.*,t2.idnumber,t2.name "+addSql+" from cm t, basicinfo t2 where t.indexcode=t2.indexcode and t.checkdate>'" + checkdate + "' order by t.checkdate asc";
				List cmList   = mBaseDao.findBySql(sql, Map.class, null);
				sql = "select t2.* "+addSql+" from cm  t,cm2 t2 where t.indexcode=t2.indexcode and t.checkdate>'" + checkdate + "'  order by t.checkdate asc";
				List cm2List =   mBaseDao.findBySql(sql, Map.class,  null);
				int cmSize=cmList.size();
				int cm2Size=cm2List.size();
				List<List> subcmList=subList(cmList, 50);
				List<List> subcm2List=subList(cm2List, 50);
				logger.info(new Date()+"==查询数据完成准备上传");
				for(List cmListTemp:subcmList){
					sendRestData(cmListTemp, null);
					
				}
				for(List cm2ListTemp:subcmList){
					sendRestData(null, cm2ListTemp);
				}

				logger.info(new Date()+"==数据上传完成:结果数据="+cmSize+"条;详细数据="+cm2Size+"条;");
			} else {

				logger.info(new Date()+"==开始查询数据准备上传");
				String addSql = " ,'" + cu.getAreaCode() + "'  as areaCode ";
				
				String sql = "select t.*,t2.idnumber,t2.name "+addSql+" from cm  t, basicinfo t2 where t.indexcode=t2.indexcode   order by t.checkdate asc";
				List cmList = mBaseDao.findBySql(sql, Map.class, null);
				sql = "select t2.* "+addSql+" from cm  t,cm2 t2 where t.indexcode=t2.indexcode order by t.checkdate asc";
				List cm2List = mBaseDao.findBySql(sql, Map.class,  null);
				int cmSize=cmList.size();
				int cm2Size=cm2List.size();
		   		List<List> subcmList=subList(cmList, 50);
				List<List> subcm2List=subList(cm2List, 50); 
				
			/*	List<List> subcmList=new ArrayList<List>();
				  subcmList.add(cmList);
				  List<List>  subcm2List=new ArrayList<List>();
				  subcm2List.add(cm2List);*/
				logger.info(new Date()+"==查询数据完成开始上传");
				for(List cmListTemp:subcmList){
					sendRestData(cmListTemp, null);
					
				}
				for(List cm2ListTemp:subcm2List){
					sendRestData(null, cm2ListTemp);
				}
				logger.info(new Date()+"==数据上传完成:结果数据="+cmSize+"条;详细数据="+cm2Size+"条;");
				
			}
		} catch (Exception e) {
			e.printStackTrace();
			 Map map = new HashMap();
		        map.put("mBaseDao", mBaseDao);
		        map.put("uploadUrl", cu.getUploadUrl());
		        map.put("cu", cu);
		     QuartzFactoryUtil.getInstance().removeJobByCalendar(UploadDataJobTask.defaultJobName, UploadDataJobTask.defaultJobName);
			 QuartzFactoryUtil.getInstance().addJobByCalendar(UploadDataJobTask.defaultJobName, UploadDataJobTask.defaultJobName, UploadDataJobTask.class, cu.getUploadIntSeconds(), map);
		}
	}

	private Map getRestData(String areaCode) {
		Map object = null;
		try {
			ResponseEntity<String> result = RestClientUtil.getInstace().restTemplate.getForEntity(uploadUrl + "/tzData/getlastCmTime?areaCode={areaCode}",String.class,new HashMap(){{
				put("areaCode", areaCode);
			}});
			String responseContent = result.getBody();
			object= JSON.parseObject(result.getBody());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return object;
	}

	private void sendRestData(List cmList, List cm2List) {
		cmList=cmList==null?new ArrayList<>():cmList;
		cm2List=cm2List==null?new ArrayList<>():cm2List;
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
		map.add("cmList", JSONUtils.toJSONString(cmList));
		map.add("cm2List", JSONUtils.toJSONString(cm2List));
		HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
		ResponseEntity<Map> response = RestClientUtil.getInstace().restTemplate
				.postForEntity(uploadUrl + "/tzData/postCmDatas", request, Map.class);
//		logger.info(new Date()+"==数据上传完成response=="+response);
		 
	}
	public  List<List> subList(List  oldList,Integer num){
		List<List> result=new ArrayList<List>();
		// 分批处理
		if (null != oldList && oldList.size() > 0) {
			Integer pointsDataLimit = num;// 限制条数
			Integer size = oldList.size();
			// 判断是否有必要分批
			if (pointsDataLimit < size) {
				int part = size / pointsDataLimit;// 分批数
				for (int i = 0; i < part; i++) {
					List  listPage = oldList.subList(0, pointsDataLimit);
					List tl=new ArrayList<>();
					tl.addAll(listPage);
					result.add(tl);
					// 剔除
					oldList.subList(0, pointsDataLimit).clear();
				}
				if(oldList.size()>0){
					
					List tl=new ArrayList<>();
					tl.addAll(oldList);
					result.add(tl);
				}

			}
		}
		return result;
	}

}
